package com.rabbitMQ.consume;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 接受消息的类
 */
public class Consume_Consumer_Topic_1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.23.129"); // 设置连接 ip 默认 localhost
        factory.setPort(5672);  // 设置连接端口 默认 5672
        factory.setVirtualHost("/root"); // 虚拟机 我们这里使用 /root
        factory.setUsername("root");    // 拥有权限的用户
        factory.setPassword("root");    // 拥有权限的用户密码

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("work_queues", true, false, false, null);
        /*
        basicConsume(String queue, boolean autoAck, Consumer callback)
        参数：
            1. queue：队列名称
            2. autoAck：是否自动确认
            3. callback：回调对象
         */
        channel.basicConsume("topic_queue1", true, new DefaultConsumer(channel) {
            /**
             * @param consumerTag 标识
             * @param envelope 获取一些信息，交换机，路由key...
             * @param properties 配置信息
             * @param body 数据
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
            }
        });
    }
}